package com.zzyl.nursing.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.huaweicloud.sdk.iotda.v5.IoTDAClient;
import com.huaweicloud.sdk.iotda.v5.model.*;
import com.zzyl.common.constant.CacheConstants;
import com.zzyl.common.core.domain.AjaxResult;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.StringUtils;
import com.zzyl.common.utils.uuid.UUID;
import com.zzyl.nursing.domain.Device;
import com.zzyl.nursing.dto.DeviceDto;
import com.zzyl.nursing.mapper.DeviceMapper;
import com.zzyl.nursing.service.IDeviceService;
import com.zzyl.nursing.vo.DeviceDetailVo;
import com.zzyl.nursing.vo.ProductVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import cn.hutool.core.bean.BeanUtil;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.util.*;

/**
 * 设备Service业务层处理
 *
 * @author ruoyi
 * @date 2025-01-14
 */
@Service
@Slf4j
public class DeviceServiceImpl extends ServiceImpl<DeviceMapper, Device> implements IDeviceService {

    @Autowired
    private DeviceMapper deviceMapper;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Autowired
    private IoTDAClient client;

    /**
     * 查询设备列表
     *
     * @param device 设备
     * @return 设备集合
     */
    @Override
    public List<Device> selectDeviceList(Device device) {
        return deviceMapper.selectDeviceList(device);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void syncProductList() {
        // 去物联网平台查询产品数据
        ListProductsRequest request = new ListProductsRequest();
        request.setLimit(50);
        ListProductsResponse response = client.listProducts(request);
        if (response.getHttpStatusCode() != 200) {
            throw new BaseException("物联网平台查询产品，同步失败！");
        }
        // 存储到redis
        redisTemplate.opsForValue().set(CacheConstants.IOT_ALL_PRODUCT_LIST, JSONUtil.toJsonStr(response.getProducts()));
    }

    @Override
    public List<ProductVo> allProduct() {
        String jsonString = redisTemplate.opsForValue().get(CacheConstants.IOT_ALL_PRODUCT_LIST);
        if (StringUtils.isEmpty(jsonString)) {
            return Collections.emptyList();
        }
        return JSONUtil.toList(jsonString, ProductVo.class);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void register(DeviceDto deviceDto) {
        // 判断设备名称是否重复 select count(*) from device where name = ?
        LambdaQueryWrapper<Device> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Device::getDeviceName, deviceDto.getDeviceName());
        if (count(queryWrapper) > 0) {
            throw new BaseException("设备名称已存在，请重新输入");
        }
        // 判断设备标识码是否重复
        LambdaQueryWrapper<Device> queryWrapperNodeId = new LambdaQueryWrapper<>();
        queryWrapperNodeId.eq(Device::getDeviceName, deviceDto.getDeviceName());
        if (count(queryWrapperNodeId) > 0) {
            throw new BaseException("设备标识码已存在，请重新输入");
        }
        // 判断同一位置是否绑定了同一产品
        LambdaQueryWrapper<Device> condition = isRebind(deviceDto);
        if (count(condition) > 0) {
            throw new BaseException("该老人/位置已绑定该产品，请重新选择");
        }
        // 新增设备 iot mysql
        AddDeviceRequest request = new AddDeviceRequest();
        AddDevice body = new AddDevice();
        AuthInfo authInfobody = new AuthInfo();
        String secret = UUID.randomUUID().toString().replaceAll("-", "");
        authInfobody.withSecret(secret);
        body.withAuthInfo(authInfobody);

        body.withProductId(deviceDto.getProductKey());
        body.withDeviceName(deviceDto.getDeviceName());
        body.withNodeId(deviceDto.getNodeId());

        request.withBody(body);
        AddDeviceResponse response;

        try {
            // 写入到华为云
            response = client.addDevice(request);
            System.out.println(response.toString());
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("物联网接口-注册设备，调用失败");
        }

        // 写入到数据库
        Device device = BeanUtil.toBean(deviceDto, Device.class);
        device.setIotId(response.getDeviceId());
        device.setSecret(secret);
        try {
            save(device);
        } catch (Exception e) {
            throw new BaseException("同一位置不能绑定同类型产品");
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public DeviceDetailVo queryDeviceDetail(String iotId) {
        // 查询数据库
        // 使用 LambdaQueryWrapper 就不需要再写 XML mapper 文件了
        // MyBatis Plus 会自动将实体类名转换为数据库表名：
        // Device → device （首字母小写）
        // UserInfo → user_info （驼峰转下划线）
        Device device = getOne(Wrappers.<Device>lambdaQuery().eq(Device::getIotId, iotId));
        System.out.println("queryDeviceDetail_device:" + device);
        if (ObjectUtil.isNull(device)) {
            return null;
        }
        // 华为云接口调用查询数据
        ShowDeviceRequest request = new ShowDeviceRequest();
        request.setDeviceId(iotId);
        ShowDeviceResponse response;
        try {
            response = client.showDevice(request);
        } catch (Exception e) {
            throw new BaseException("物联网接口-查询设备详情，调用失败");
        }
        // 组合数据
        DeviceDetailVo deviceDetailVo = BeanUtil.toBean(device, DeviceDetailVo.class);
        deviceDetailVo.setDeviceStatus(response.getStatus());
        String activeTimeStr = response.getActiveTime();
        if (StringUtils.isNotBlank(activeTimeStr)) {
            LocalDateTime activeTime = LocalDateTimeUtil.parse(activeTimeStr, DatePattern.UTC_MS_PATTERN);
            // 时区转换
            activeTime = activeTime.atZone(ZoneId.from(ZoneOffset.UTC))
                    .withZoneSameInstant(ZoneId.of("Asia/Shanghai"))
                    .toLocalDateTime();
            deviceDetailVo.setActiveTime(activeTime);
        }
        return deviceDetailVo;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult queryServiceProperties(String iotId) {
        // 调用iot平台接口查询数据
        ShowDeviceShadowRequest request = new ShowDeviceShadowRequest();
        request.setDeviceId(iotId);
        ShowDeviceShadowResponse response = client.showDeviceShadow(request);
        if (response.getHttpStatusCode() != 200) {
            throw new BaseException("物联网接口-查看设备上报的数据，调用失败");
        }
        List<DeviceShadowData> shadow = response.getShadow();
        if (CollUtil.isEmpty(shadow)) {
            return AjaxResult.success(Collections.emptyList());
        }
        System.out.println("queryServiceProperties_shadow:" + shadow);
        // 对数据进行处理
        JSONObject jsonObject = JSONUtil.parseObj(shadow.get(0).getReported().getProperties());
        ArrayList<Map<String, Object>> list = new ArrayList<>();
        // 处理上报时间
        LocalDateTime activeTime = LocalDateTimeUtil.parse(shadow.get(0).getReported().getEventTime(), "yyyyMMdd'T'HHmmss'Z'");
        LocalDateTime eventTime = activeTime.atZone(ZoneId.from(ZoneOffset.UTC))
                .withZoneSameInstant(ZoneId.of("Asia/Shanghai"))
                .toLocalDateTime();

        jsonObject.forEach((k, v) -> {
            HashMap<String, Object> map = new HashMap<>();
            map.put("functionId", k);
            map.put("value", v);
            map.put("eventTime", eventTime);
            list.add(map);
        });
        return AjaxResult.success(list);
    }

    @Override
    @Transactional(rollbackFor = Exception.class) // 添加事务注解
    public AjaxResult updateDevice(DeviceDto deviceDto) {
        // 1. 参数校验
        if (deviceDto.getId() == null) {
            return AjaxResult.error("设备ID不能为空");
        }

        // 2. 检查设备是否存在
        Device existingDevice = getById(deviceDto.getId()); // 直接用getById更简单
        if (existingDevice == null) {
            return AjaxResult.error("设备不存在");
        }

        // 3. 检查重复绑定（同一位置+同一产品）
        LambdaQueryWrapper<Device> condition = isRebind(deviceDto);
        if (count(condition) > 0) {
            throw new BaseException("该老人/位置已绑定该产品，请重新选择");
        }

        // 4. 复制属性
        Device device = BeanUtil.toBean(deviceDto, Device.class);
        device.setIotId(existingDevice.getIotId()); // 保持iotId不变
        device.setDeviceDescription(existingDevice.getDeviceDescription());

        // 5. 先更新华为云（外部服务先调用）
        try {
            UpdateDeviceRequest request = new UpdateDeviceRequest();
            request.setDeviceId(device.getIotId());

            UpdateDevice body = new UpdateDevice();
            AuthInfoWithoutSecret authInfo = new AuthInfoWithoutSecret();
            authInfo.withSecureAccess(true);

            body.withAuthInfo(authInfo)
                    .withDeviceName(device.getDeviceName())
                    .withDescription(device.getDeviceDescription());

            request.withBody(body);

            UpdateDeviceResponse response = client.updateDevice(request);

            // 检查华为云响应是否成功
            if (response.getHttpStatusCode() != 200) {
                throw new BaseException("华为云设备更新失败");
            }

        } catch (Exception e) {
            log.error("华为云设备更新失败: {}", e.getMessage());
            throw new BaseException("物联网接口调用失败: " + e.getMessage());
        }

        // 6. 更新数据库（外部服务成功后再更新本地）
        boolean updateSuccess = updateById(device);
        if (!updateSuccess) {
            throw new BaseException("数据库更新失败");
        }

        return AjaxResult.success("设备更新成功");
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult deleteDevice(String iotId) {
        // 参数校验
        if (StringUtils.isBlank(iotId)) {
            return AjaxResult.error("设备ID不能为空");
        }

        // 先查询数据库中的设备信息（用于后续操作和验证）
        Device device = getOne(
                new LambdaQueryWrapper<Device>()
                        .eq(Device::getIotId, iotId)
        );

        if (device == null) {
            return AjaxResult.error("设备不存在或已被删除");
        }

        // 删除华为云设备
        DeleteDeviceRequest request = new DeleteDeviceRequest();
        request.withDeviceId(iotId);
        try {
            client.deleteDevice(request);
        } catch (Exception e) {
            log.error("华为云设备删除失败: {}", e.getMessage());
            throw new BaseException("物联网接口调用失败: " + e.getMessage());
        }

        // 删除数据库中的设备记录
        boolean deleteSuccess = remove(
                new LambdaQueryWrapper<Device>()
                        .eq(Device::getIotId, iotId)
        );

        if (!deleteSuccess) {
            log.warn("数据库设备记录删除失败，但华为云设备已删除，iotId: {}", iotId);
            throw new BaseException("数据库设备删除失败");
        }

        // 删除所有与该设备关联的人/物

        log.info("设备删除成功，iotId: {}", iotId);
        return AjaxResult.success("设备删除成功");
    }

    @Override
    public AjaxResult queryProduct(String productKey) {
        // 参数校验
        if (StringUtils.isEmpty(productKey)) {
            throw new BaseException("请输入正确的参数");
        }
        // 调用华为云接口
        ShowProductRequest request = new ShowProductRequest();
        request.withProductId(productKey);
        ShowProductResponse response;
        try {
            response = client.showProduct(request);
        } catch (Exception e) {
            throw new BaseException("物联网接口调用失败: " + e.getMessage());
        }
        List<ServiceCapability> serviceCapabilities = response.getServiceCapabilities();
        if (CollUtil.isEmpty(serviceCapabilities)) {
            return AjaxResult.success(Collections.emptyList());
        }
        return AjaxResult.success(serviceCapabilities);
    }

    private static LambdaQueryWrapper<Device> isRebind(DeviceDto deviceDto) {
        LambdaQueryWrapper<Device> condition = new LambdaQueryWrapper<>();
        condition.eq(Device::getProductKey, deviceDto.getProductKey())
                .eq(Device::getLocationType, deviceDto.getLocationType())
                .eq(Device::getPhysicalLocationType, deviceDto.getPhysicalLocationType())
                .eq(Device::getBindingLocation, deviceDto.getBindingLocation());
        return condition;
    }

}
